<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ErrorCode;
use App\Model\Service\CacheService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class UserActMiddleware implements MiddlewareInterface
{
    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var HttpResponse
     */
    protected $response;

    //限制接口
    public $lmtRoutes  = [
        //聊天检测
        '/message/v1_1_4/chat/charge',
        //发布动态
        '/moment/publish',
        //动态留言
        '/moment/comment',
        //呼叫通话
        '/index/call_video',
        '/index/call',
        //随心聊
        '/message/v1_1_0/quick_call',
        '/message/v1_1_2/quick_call',
        //一键搭讪
        '/message/v1_0_4/chat/quick',
        //开启聊天
        '/message/chat/start',
    ];

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $forbidUsers = CacheService::getForbiddenUsers();
        $request = Context::get(ServerRequestInterface::class);
        $userId = $request->getAttribute('userId');
        log_info(__METHOD__ . "=={$userId}");
        if ($userId && in_array($userId, $forbidUsers)) {
            $params = $request->getServerParams();
            $path = $params['path_info'];
            if (in_array($path, $this->lmtRoutes)) {
                return $this->response->json([
                    'ret' => -1,
                    'result' => ErrorCode::USER_FORBIDDEN,
                    'res_info' => '你当前在禁言状态，暂无法操作～'
                ]);
            }
        }
        return $handler->handle($request);
    }
}
